package main

import (
	"fmt"
	"sync"
	"strings"
	"time"
	"encoding/json"
)

type ZbMarket struct {
	Amount   int `json:"amountScale"`
	Price int `json:"priceScale"`
}

func ZbMarketList() []byte {

	url := "http://api.zb.com/data/v1/markets"

	body := httpGet(url)

	return body
}



func ZbMarketToRedis(name string, wg *sync.WaitGroup){
	defer wg.Done()

	url := "http://api.zb.com/data/v1/ticker?market=" + strings.ToLower(name)

	body := httpGet(url)

	key := "Zb_" + name + "_Latest"
    
	err := client.Set(key, body, 0).Err()
	if err != nil {
		fmt.Printf("Error: %s\n", err)
	}else{
		//fmt.Printf("Success write: %s\n", key)
	}

}

func ZbMarketsToRedis(inWg *sync.WaitGroup) error{
	defer inWg.Done()

	t := time.Now()
	// fmt.Printf("ZbMarketsToRedis begin.\n")


	var wg sync.WaitGroup
    
    var mdata map[string]ZbMarket
    var data []byte = ZbMarketList()
    
    err := json.Unmarshal(data, &mdata)
    if err != nil {
    	fmt.Printf("error: %s\n", err)
    }
    

	for key, _:= range mdata {
		wg.Add(1)
		//fmt.Printf("ZbMarketToRedis(%s) begin.\n", market)
		go ZbMarketToRedis(key, &wg)
	}

	wg.Wait()

    fmt.Printf("ZbMarketsToRedis duration: %s\n", time.Now().Sub(t))

	return nil
}
